package medium

import (
	"strconv"
	"strings"
)

// validIPAddress https://leetcode.cn/problems/validate-ip-address/
func validIPAddress(queryIP string) string {
	if strings.Contains(queryIP, ".") {
		ipv4 := strings.Split(queryIP, ".")
		if len(ipv4) != 4 {
			return "Neither"
		}
		for _, s := range ipv4 {
			if len(s) > 3 || len(s) < 1 {
				return "Neither"
			}
			ipNum, _ := strconv.Atoi(s)
			if ipNum > 255 || len(s) != len(strconv.Itoa(ipNum)) {
				return "Neither"
			}
		}
		return "IPv4"
	}
	if strings.Contains(queryIP, ":") {
		ipv6 := strings.Split(queryIP, ":")
		if len(ipv6) != 8 {
			return "Neither"
		}

		for _, s := range ipv6 {
			if len(s) < 1 || len(s) > 4 {
				return "Neither"
			}
			for _, ch := range s {
				if !(ch >= '0' && ch <= '9') && !(ch >= 'a' && ch <= 'f' || ch >= 'A' && ch <= 'F') {
					return "Neither"
				}
			}
		}
		return "IPv6"
	}
	return "Neither"
}
